package com.ncu.uibroadcast;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button b1,b2;
    ProgressBar pb;
    TextView tv;
    MyReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         b1=(Button)findViewById(R.id.button);
         b2=(Button)findViewById(R.id.button2);
         b1.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 startService(new Intent(MainActivity.this, MyService.class));
                 //开始服务
                 receiver=new MyReceiver();
                 //这么写就可以不用再AndroidManifest中注册了，直接可以
                 IntentFilter filter=new IntentFilter();
                 filter.addAction("com.ncu.uibroadcast.MyReceiver");
                 MainActivity.this.registerReceiver(receiver,filter);
             }
         });
         b2.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 stopService(new Intent(MainActivity.this, MyService.class));
                 MainActivity.this.unregisterReceiver(receiver);
             }//关闭服务
         });
         pb=(ProgressBar)findViewById(R.id.progressBar);
         tv=(TextView)findViewById(R.id.textView);
    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("OnReceiver");
            //广播进行发送到UI
            Bundle bundle=intent.getExtras();
            int a=bundle.getInt("i");
            pb.setProgress(a);
            tv.setText(String.valueOf(a));
            //处理接收到的内容
        }
    }

}
